package com.example.shiroplusdemo.service;

import com.example.shiroplusdemo.entity.FrontPage;
import com.example.shiroplusdemo.entity.Role;
import com.example.shiroplusdemo.repository.RoleRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;

/**
 * @author ：Anitaxiaofeng
 * @description：
 * @create 2018-01-12
 **/
@Service
@Slf4j
public class RoleService {

    @Autowired
    private RoleRepository roleRepository;

    public Page<Role> getRoleList(FrontPage page){
        Sort.Order order = new Sort.Order(Sort.Direction.ASC,page.getSidx());
        Sort sort = new Sort(order);
        Pageable pageable = new PageRequest(page.getPage(),page.getRows(),sort);
        if(page.getKeywords()==null){
            return roleRepository.findAll(pageable);
        }
        Specification<Role> specification = new Specification<Role>() {
            @Override
            public Predicate toPredicate(Root<Role> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Path<String> path = root.get("name");
                return cb.like(path,"%"+page.getKeywords()+"%");
            }
        };
        Page<Role> rolePage = roleRepository.findAll(specification,pageable);
        return rolePage;
    }
}
